import PageContainer from '@/components/PageContainer';
import { Text, View, Image } from '@tarojs/components';
import { Button } from '@tarojs/components';
import I18n from 'i18n-js';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import Taro from '@tarojs/taro';
import ListItem from '@/components/ListItem';
import Switch from '@/components/Switch';
import { GButton } from '@/components/GButton';
import { createAuth, deleteAuth, getAuthDevices, getAuthState } from '@/services/ai';
import Alert from '@/components/Alert';

const styles = {
  container: {
    padding: 20,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  subTitle: {
    marginTop: 20,
  },
  logo: {
    width: 120,
    height: 40,
    marginBottom: 30,
    marginTop: 20,
    alignSelf: 'center'
  },
  selectDeviceContainer: {
    textAlign: 'center',
  },
  tipsContent: {
    paddingBottom: 20,
    paddingLeft: 20,
    paddingTop: 10,
    paddingRight: 20,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  authCode: {
    fontSize: 24,
    color: '#1890ff',
    paddingTop: 10,
    paddingBottom: 10,
  },
  countdown: {
    fontSize: 14,
    color: '#999',
    marginTop: 5,
    marginBottom: 10,
  },
  inlineButton: {
    display: 'inline-block',
    marginLeft: 10,
  },
  button: {
    borderRadius: 4,
    fontSize: 14,
    color: '#fff',
    padding: "6px 10px 6px 10px",
    backgroundColor: '#1890ff',
  },
  bottomButton: {
    position: 'absolute',
    bottom: 20,
    padding: '14px 20px 14px 20px',
    width: '80%',
    left: '5%',
  },
  title: {
    width: '100%',
    textAlign: 'left',
    fontSize: 16,
    paddingTop: 20,
    paddingLeft: 20,
    paddingRight: 20,
    boxSizing: 'border-box',
    marginBottom: 10,
  },
  content: {
    display: 'flex',
    flex: 1,
  },
  desc: {
    fontSize: 14,
    color: '#666',
    lineHeight: 1.5,
    boxSizing: 'border-box',
    padding: '0 20px'
  },
  confirmButton: {
    position: 'absolute',
    bottom: 30,
    color: '#fff',
    marginLeft: '10%',
    backgroundColor: '#1890ff',
    width: '80%',
  },
  link: {
    color: '#1890ff',
    textDecoration: 'underline',
  }
};

export default function ThirdPlatform() {
  const [authState, setAuthState] = useState(0)
  const [link, setLink] = useState('')
  const [code, setCode] = useState('')
  const [devLength, setDevLength] = useState(0)
  const interval: any = useRef(null)
  const countdownTimer: any = useRef(null)
  const [showAlert, setShowAlert] = useState(false)
  const [expiresAt, setExpiresAt] = useState(0)
  const [countdown, setCountdown] = useState('')

  useEffect(() => {
    getAuthStateFunc().then((res) => {
      if (res.success && res.data.data.state === 1) {
        // 授权中的状态，需要轮训
        createAuthFunc();
      }
    })

    return () => {
      clearAllTimers();
    }
  }, []);

  useEffect(() => {
    if (authState === 1) {
      interval.current = setInterval(() => {
        getAuthStateFunc().then((res) => {
          if (res.success && res.data.data.state === 2) {
            clearInterval(interval.current)
          }
        })
      }, 1000)
    }
  }, [authState])

  // 处理倒计时
  useEffect(() => {
    if (expiresAt > 0) {
      startCountdown();
    }
    
    return () => {
      if (countdownTimer.current) {
        clearInterval(countdownTimer.current);
      }
    }
  }, [expiresAt]);

  const startCountdown = () => {
    // 清除之前的倒计时
    if (countdownTimer.current) {
      clearInterval(countdownTimer.current);
    }

    // 设置新的倒计时
    countdownTimer.current = setInterval(() => {
      const now = Math.floor(Date.now() / 1000);
      const timeLeft = expiresAt - now;
      
      if (timeLeft <= 0) {
        // 倒计时结束，刷新授权码
        clearInterval(countdownTimer.current);
        createAuthFunc();
        return;
      }
      
      // 格式化倒计时显示
      const minutes = Math.floor(timeLeft / 60);
      const seconds = timeLeft % 60;
      setCountdown(`${minutes}:${seconds < 10 ? '0' : ''}${seconds}`);
    }, 1000);
  }

  const clearAllTimers = () => {
    if (interval.current) {
      clearInterval(interval.current);
      interval.current = null;
    }
    
    if (countdownTimer.current) {
      clearInterval(countdownTimer.current);
      countdownTimer.current = null;
    }
  }

  const getAuthStateFunc = async () => {
    const res = await getAuthState()
    if (res.success) {
      setAuthState(res.data.data.state)
    }
    return res;
  }

  const reloadData = async () => {
    const res = await getAuthState()
    // 0 1 授权中 2 授权成功
    if (res.data.data.state === 2) {
      const devices = await getAuthDevices()
      if (devices.success) {
        setDevLength(devices.data.data.length)
      }
    }
    return res;
  }

  const createAuthFunc = async () => {
    const res = await createAuth()
    console.log('createAuth', res)
    if (res.success) {
      setAuthState(1)
      setLink(res.data.data.auth_url)
      setCode(res.data.data.auth_code)
      
      // 设置过期时间并启动倒计时
      if (res.data.data.expire_time) {
        setExpiresAt(res.data.data.expire_time)
      }
    }
    return res;
  }

  const onHide = () => {
    clearAllTimers();
  }

  const onShow = async () => {
    // 页面重新显示时，刷新数据
    const res = await reloadData();
    
    // 如果是授权中状态，检查是否需要重新创建授权
    if (res.success && res.data.data.state === 1) {
      // 如果过期时间已过或者接近过期，重新创建授权
      const now = Math.floor(Date.now() / 1000);
      if (expiresAt <= now || expiresAt - now < 60) {
        createAuthFunc();
      } else {
        // 否则重新启动倒计时
        startCountdown();
      }
    }
  }

  return (
    <PageContainer onHide={onHide} onShow={onShow} title={I18n.t("扣子 Coze")}>
      <SelectDeviceComponent
        onReload={async () => {
          Taro.showLoading({
            title: I18n.t('加载中...'),
          })
          const data = await reloadData()
          Taro.hideLoading()
          if (data.success && data.data.data.state === 1) {
            Taro.showToast({
              title: I18n.t('暂未查询到授权信息'),
              icon: 'none',
            })
          }
        }}
        onRefreshCode={async () => {
          const res = await createAuthFunc();
        }}
        link={link} 
        code={code}
        countdown={countdown}
        onReload={async () => {
          Taro.showLoading({
            title: I18n.t('加载中...'),
          })
          const data = await reloadData()
          Taro.hideLoading()
          if (data.success && data.data.data.state === 1) {
            Taro.showToast({
              title: I18n.t('暂未查询到授权信息'),
              icon: 'none',
            })
          }
        }}
        authState={authState}
        onAuth={async () => {
          if (authState === 1 || authState === 2) {
            // 先弹窗
            setShowAlert(true)
          }
          if (authState == 0) {
            const res = await createAuthFunc();
          }
        }}></SelectDeviceComponent>

      <Alert
        title={'解除授权'}
        subTitle={'解除授权后，扣子智能体将会消失'}
        visible={showAlert}
        okText="确定解除"
        onCancel={() => {
          setShowAlert(false)
        }}
        onConfirm={async () => {
          const res = await deleteAuth()
          console.log('deleteAuth', res)
          if (res.success) {
            setAuthState(0)
            Taro.showToast({
              title: I18n.t('取消授权成功'),
              icon: 'success',
            })
          }
          setShowAlert(false)
        }}
      />
    </PageContainer>
  );
}

const SelectDeviceComponent = ({ link, code, countdown, authState, onAuth, onReload, onRefreshCode }) => {
  const goToHelpCenter = () => {
    Taro.navigateTo({ url: '/pages/FAQ/index?title=如何授权扣子Coze&parent_id=1932&id=1933' })
  }
  
  const extra = useMemo(() => {
    if (authState === 0) {
      return <View style={styles.button} onClick={() => {
        onAuth()
      }}>
        去授权
      </View>
    }
  }, [authState])
  
  return (
    <View style={styles.selectDeviceContainer}>
      <ListItem extra={extra}>
        {
          authState === 2 ? '扣子智能体' : '添加扣子智能体'
        }
      </ListItem>

      {
        authState === 2 && (
          <>
            <ListItem extra={<Text style={{ color: '#1890ff' }}>授权成功</Text>} style={{ marginTop: 20 }}>
              授权状态
            </ListItem>

            <ListItem arrow onClick={() => Taro.navigateTo({ url: '/pages/thirdPlatform/devices' })} style={{ marginTop: 20 }}>
              配置智能体到设备
            </ListItem>

            <View onClick={() => {
              onAuth();
            }} style={{ ...styles.button, ...styles.bottomButton }}>
              解除授权
            </View>
          </>
        )
      }

      {
        authState === 0 && (
          <>
            <View style={{ height: 20 }} />
            <View style={styles.desc}>
              {I18n.t('添加扣子智能体到开发版之前需要先到扣子平台上进行机智云渠道的授权')}
            </View>
            <View onClick={goToHelpCenter} style={{ ...styles.link, marginTop: 10 }}>
              {I18n.t('如何授权扣子Coze？')}
            </View>
          </>
        )
      }
      {
        authState === 1 ? (
          <>
            <View style={{ backgroundColor: '#fff' }}>
              <View style={styles.title}>
                1、点击下方按钮复制扣子授权链接
              </View>
              <View style={styles.title}>
                2、用浏览器打开扣子授权页
                <View style={{ ...styles.button, ...styles.inlineButton }} onClick={() => {
                  Taro.setClipboardData({
                    data: `${link}?user_code=${code}`,
                  })
                  Taro.showToast({
                    title: I18n.t('复制成功'),
                    icon: 'success',
                  })
                }}>
                  复制链接
                </View>
              </View>
              <View style={{...styles.title, paddingBottom: 10}}>
                3、在授权页中点击下一步
              </View>

            </View>

            <ListItem style={{ marginTop: 10 }} extra={(
              <>
                <View style={{ color: '#1890ff' }}>
                  等待授权完成
                </View>
                <View style={{...styles.button, marginLeft: 10}} onClick={() => {
                  onReload();
                }}>我已授权</View>
              </>
            )}>
              授权状态
            </ListItem>

            <View onClick={goToHelpCenter} style={{ ...styles.link, marginTop: 40 }}>
              {I18n.t('如何授权扣子Coze？')}
            </View>
          </>
        ) : null
      }
    </View>
  );
};